from google.appengine.ext import webapp 
from google.appengine.api import taskqueue
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api import mail


import logging
import email
import string 
import cachedstore

from models import *
from updatetasks import *
from datetime import *

class LogSenderHandler(InboundMailHandler):
    def receive(self, email): 
          
        logging.info("Incoming email from %s", email.sender)
        
        emailcheck = email.sender.lower()        
        if not "nikola.tepper@gmail.com" in emailcheck and not "calibre@kindly.cz" in emailcheck:
            logging.warn("Email from unapproved sender %s! Skipping processing", emailcheck)
            return
        
        attachments = get_attachments(email)
        if len(attachments) < 1:
            logging.warn("Email contains no attachments")
            return           
            
        # get attachment name, prepare other terms
        filename, content = attachments[0]         
        
        filecontent = content.decode()
        filesizeKb = int(len(filecontent)/1024)
        
        logging.debug("Received %s, size %i Kb. Saving to blobstore", filename, filesizeKb)        
        blob_key = cachedstore.save(filename, filecontent)        
        
        update = UpdatePeriodical()
        update.updateDeferred(str(blob_key), filename, filesizeKb, datetime.now())        
                     
def get_attachments(email):
    attachments = []
    #if email.attachments: #AttributeError: 'InboundEmailMessage' object has no attribute 'attachments'
    if hasattr(email, 'attachments'):
        if isinstance(email.attachments[0], basestring):
            attachments = [email.attachments]
        else:
            attachments = email.attachments
    return attachments
        
        
application = webapp.WSGIApplication([LogSenderHandler.mapping()], debug=True)

def main():
   run_wsgi_app(application)
 
if __name__ == '__main__':
    main()